from flask import request, Blueprint, send_file
from services import service_img as img
import os

img_blue = Blueprint('img', __name__)
basedir = os.path.abspath(os.path.dirname(__file__))


@img_blue.route('/img', methods=['post'])
def getImg():
    role = request.form.get('role')
    ID = request.form.get('ID')
    imgData = request.files["image"]
    # 设置图片要保存到的路径
    path = basedir + "/../img/" + role + "/"
    pathWithoutBase = "/../img/" + role + "/"
    # 获取图片名称及后缀名
    imgName = imgData.filename
    # 图片path和名称组成图片的保存路径
    filePath = pathWithoutBase + imgName
    file_path = path + imgName
    print(filePath)
    # 向数据库中插入profile_photo
    img.saveImgPath(role, ID, filePath)
    # service.update({"ID":ID,"profile_photo":filePath})
    # 保存图片
    imgData.save(file_path)
    # url是图片的路径
    url = '/static/upload/img/' + imgName
    return 'ok'


@img_blue.route('/img', methods=['get'])
def responseImg():
    role = request.args.get('role')
    ID = request.args.get('ID')
    imgDir = img.getImgs(role, ID)
    if imgDir.endswith('None'):
        return 'error'
    return send_file(imgDir)
